package haha.life.normal;

import cnki.tpi.base.DataContext;
import cnki.tpi.base.DataSourceManager;
import com.kbase.jdbc.StatementImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description: tpi工具类
 *
 * @author BaiGe
 * @date: 2021/12/22 15:15
 * @Version 1.0
 */
@Component
public class TpiUtils {
    @Autowired
    private DataSourceManager kbaseDs;
    @Autowired
    private DataContext dataContext;

    /**
     * 将本地的REC文件数据导入到数据库中
     * @param localPath 文件所在本地路径
     * @param tableName 表名
     * @return
     */
    public Boolean insetRecFileToDb(String localPath,String tableName){
        String recStr="";
        try {
            InputStream
                    fis = new BufferedInputStream(new FileInputStream(localPath));
            recStr = FileUtil.readJsonFileFromStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        boolean insetRes = dataContext.insertRecData(tableName,recStr);
        return insetRes;
    }




    /**
     * 得到分类导航树结构(只能用于1级,2级分类导航)
     *
     * @param dataBaseCode    数据库名
     * @param isOnlyShowFirstNode 是否只展示第一级分类
     * @return
     */
    public List<Map<String, Object>> excuteQueryList(String dataBaseCode, Boolean isOnlyShowFirstNode) {
        StringBuffer sqlStr = new StringBuffer();
        sqlStr.append("select NAME,CODE,SYSCODE,SYSID,CHILDFLAG,GRADE  from " + dataBaseCode + "_CLS_NODE");
        String sql = sqlStr.toString();

        List<Map<String, Object>> result = new ArrayList();
        ResultSet rs = null;
        Connection conn = null;
        StatementImpl pst = null;

        try {
            conn = this.kbaseDs.getConnection();
            pst = (StatementImpl) conn.createStatement();
            rs = pst.executeQuery(sql);
            String[] fieldList = parserFieldList(sql);
            int count = fieldList.length;

            while (rs.next()) {
                Map<String, Object> map = new HashMap();

                for (int i = 0; i < count; ++i) {
                    String name = fieldList[i].trim();
                    String value = rs.getString(i + 1);
                    map.put(name, value);
                }

                result.add(map);
            }
        } catch (Exception var20) {
            var20.printStackTrace();
        } finally {
            try {
                if (rs != null && !rs.isClosed()) {
                    rs.close();
                }

                if (pst != null && !pst.isClosed()) {
                    pst.close();
                }

                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            } catch (Exception var19) {
                var19.printStackTrace();
            }

        }

        List<Map<String, Object>> maps = screenNode(result, isOnlyShowFirstNode);
        return maps;
    }


    private String[] parserFieldList(String sql) {
        String[] result = {};
        try {
            sql = sql.toLowerCase();
            String field = sql.substring(7, sql.indexOf("from") - 1);
            result = field.split(",");
            for (int i = 0; i < result.length; i++) {
                String str = result[i];
                if (str.contains(" as ")) {
                    int x = str.indexOf(" as ");
                    result[i] = str.substring(x + 4, str.length()).trim();
                } else {
                    result[i] = str.trim();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private List<Map<String, Object>> screenNode(List<Map<String, Object>> maps, Boolean isShowFirstNode) {
        List<Map<String, Object>> list = new ArrayList<>();
        // 2 建一个集合，记录需要删除的元素，之后统一删除
        List<Map> templist = new ArrayList<Map>();

        for (Map map : maps) {
//            if ("1".equals(map.get("childflag"))) {
            if ("1".equals(map.get("grade"))) {
                list.add(map);
                templist.add(map);
            }
        }
        maps.removeAll(templist);
        if (isShowFirstNode) {//只需要第一级分类
            return list;
        } else {
            for (Map map : list) {
                List<Map<String,String>> childList=new ArrayList<>();
//                int i=0;
                for (Map map2 : maps) {
                    //子分类的
                    String syscode_in = String.valueOf(map2.get("syscode"));
                    //父分类的
                    String syscode_out = String.valueOf(map.get("syscode"));
//                    if ("0".equals(map2.get("childflag")) && syscode_in.indexOf(syscode_out) == 0) {
                    if ("2".equals(map2.get("grade")) && syscode_in.indexOf(syscode_out) == 0) {
                        childList.add(map2);
                    }
                }
                map.put("child", childList);
            }
        }
        return list;

    }


    /**
     * 得到分类导航树结构(只能用于1级,2级分类导航)
     *
     * @param dataBaseCode    数据库名
     * @return
     */
    public List<Map<String, Object>> getDescribe(String dataBaseCode) {
       String sql="select 专题名 as name,关键词 as describe from " + dataBaseCode + "_METADATA";

        List<Map<String, Object>> result = new ArrayList();
        ResultSet rs = null;
        Connection conn = null;
        StatementImpl pst = null;

        try {
            conn = this.kbaseDs.getConnection();
            pst = (StatementImpl) conn.createStatement();
            rs = pst.executeQuery(sql);
            String[] fieldList = parserFieldList(sql);
            int count = fieldList.length;

            while (rs.next()) {
                Map<String, Object> map = new HashMap();

                for (int i = 0; i < count; ++i) {
                    String name = fieldList[i].trim();
                    String value = rs.getString(i + 1);
                    map.put(name, value);
                }

                result.add(map);
            }
        } catch (Exception var20) {
            var20.printStackTrace();
        } finally {
            try {
                if (rs != null && !rs.isClosed()) {
                    rs.close();
                }

                if (pst != null && !pst.isClosed()) {
                    pst.close();
                }

                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            } catch (Exception var19) {
                var19.printStackTrace();
            }

        }

        return result;
    }
}
